package com.splic.product.service.impl;

import cn.hutool.core.date.DateUtil;
import com.splic.common.core.DeviceContext;
import com.splic.common.core.redis.RedisCache;
import com.splic.common.enums.EmailCodeTypeEnum;
import com.splic.common.enums.ThirdUserTypeEnum;
import com.splic.common.exception.BusinessException;
import com.splic.common.gen.DistributedRidesLock;
import com.splic.common.utils.DateUtils;
import com.splic.common.utils.RandomCodeUtil;
import com.splic.common.utils.ShiroUtils;
import com.splic.common.utils.StringUtils;
import com.splic.common.utils.security.Md5Utils;
import com.splic.product.domain.*;
import com.splic.product.dto.*;
import com.splic.product.mapper.UserMapper;
import com.splic.product.mapper.UserSubRecordMapper;
import com.splic.product.mapper.UserThirdBindMapper;
import com.splic.product.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 用户信息Service业务层处理
 * 
 * @author singe
 * @date 2022-01-04
 */
@Service
public class UserServiceImpl implements UserService
{
    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserThirdBindMapper userThirdBindMapper;
    @Autowired
    private EmailSendCodeService emailSendCodeServiceImpl;
    @Autowired
    private DistributedRidesLock distributedRidesLock;
    @Autowired
    private UserService userServiceImpl;
    @Autowired
    private DeviceService deviceServiceImpl;
    @Autowired
    private ProductService productServiceImpl;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private UserSubRecordMapper userSubRecordMapper;
    @Autowired
    private ProductUserService productUserService;
    /**
     * 查询用户信息
     * 
     * @param id 用户信息主键
     * @return 用户信息
     */
    @Override
    public User selectUserById(Long id)
    {
        return userMapper.selectUserById(id);
    }

    /**
     * 查询用户信息列表
     * 
     * @param user 用户信息
     * @return 用户信息
     */
    @Override
    public List<User> selectPageList(User user)
    {
        return userMapper.selectUserList(user);
    }

    /**
     * 查询用户信息列表
     *
     * @param user 用户信息
     * @return 用户信息
     */
    @Override
    public List<User> selectUserList(User user)
    {
        if (StringUtils.isEmpty(user.getStartCreateTime())) {
            user.setStartCreateTime(DateUtil.formatDate(DateUtil.offsetDay(new Date(), -7)));
        }
        if (StringUtils.isEmpty(user.getEndCreateTime())) {
            user.setEndCreateTime(DateUtil.formatDate(DateUtil.offsetDay(new Date(), 1)));
        } else {
            user.setEndCreateTime(DateUtil.formatDate(DateUtil.offsetDay(DateUtils.parseDate(user.getEndCreateTime()), 1)));
        }
        return userMapper.selectUserList(user);
    }

    /**
     * 新增用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int insert(User user)
    {
        user.setUserIdentify(getIdentify());
        user.setCreateTime(DateUtils.getNowDate());
        if (user.getEmail() == null) {
            user.setEmail("");
        }
        if (user.getAccount() == null) {
            user.setAccount("");
        }
        Product product = productServiceImpl.getByPackageKey(DeviceContext.getProductPackageKey());
        if (product != null) {
            user.setFirstRegisterApp(product.getName());
        } else {
            user.setFirstRegisterApp("未知");
        }
        return userMapper.insert(user);
    }

    private String getIdentify(){
        String deviceIdentify = RandomCodeUtil.identifyCode("UE");
        User user = this.getByUserIdentify(deviceIdentify);
        if (user != null){
            return this.getIdentify();
        }
        return deviceIdentify;
    }
    /**
     * 修改用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int update(User user)
    {
        user.setUpdateTime(DateUtils.getNowDate());
        return userMapper.update(user);
    }


    /**
     * 删除用户信息信息
     * 
     * @param id 用户信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteById(Long id)
    {
        User user = this.selectUserById(id);
        if (user == null){
            throw new BusinessException("用户查询失败");
        }

        //删除账号  备份账号
        userMapper.logoutAccountById(id);
        UserBackUpDto userBackUpDto = new UserBackUpDto();
        BeanUtils.copyProperties(user,userBackUpDto);
        userBackUpDto.setReason("后台管理删除");
        userMapper.insertLogOutBackUp(userBackUpDto);

        //删除 三方绑定账号   备份三方绑定账号
        UserThirdBind userThirdBind = new UserThirdBind();
        userThirdBind.setUserId(id);
        List<UserThirdBind> userThirdBindList = userThirdBindMapper.selectUserThirdBindList(userThirdBind);
        if (CollectionUtils.isNotEmpty(userThirdBindList)){
            for(UserThirdBind thirdBind:userThirdBindList){

                userThirdBindMapper.deleteLogoutThirdBindById(thirdBind.getId());

                userThirdBindMapper.insertLogOutBackUp(thirdBind);
            }
        }
        return 1;
    }
    /**
     * 修改用户信息
     *
     * @param user 用户信息信息
     * @return 结果
     */
    @Override
    @Transactional
    public int saveOrUpdate(User user)
    {
        if(user.getId() != null){
            user.setUpdateTime(new Date());
            return userMapper.update(user);
        }else{
            user.setCreateTime(new Date());
            if (user.getEmail() == null) {
                user.setEmail("");
            }
            if (user.getAccount() == null) {
                user.setAccount("");
            }
            Product product = productServiceImpl.getByPackageKey(DeviceContext.getProductPackageKey());
            if (product != null) {
                user.setFirstRegisterApp(product.getName());
            } else {
                user.setFirstRegisterApp("未知");
            }
            return userMapper.insert(user);
        }
    }

    @Override
    public User getByAccount(String account) {
        return userMapper.getByAccount(account);
    }

    @Override
    public User getByEmail(String email) {
        return userMapper.getByEmail(email);
    }


    @Override
    public User getByUserIdentify(String userIdentify) {
        return userMapper.getByUserIdentify(userIdentify);
    }
    /**
     * 用户注册
     * @param registerDto
     */
    @Override
    public Long register(RegisterDto registerDto) {
        String key = "user:register:"+registerDto.getAccount();
        final String lock= distributedRidesLock.lock(key,3);
        try {
            if (null == lock) {
                throw new BusinessException("操作过于频繁，请您稍后再试。");
            }

            User user = getByAccount(registerDto.getAccount());
            if (user != null) {
                throw new BusinessException("该手机号已注册，请您直接登录。");
            }
            User userTwo = getByEmail(registerDto.getEmail());
            if (userTwo != null) {
                throw new BusinessException("该邮箱已注册，请您直接登录。");
            }

            String new_user_pwd = Md5Utils.hash(registerDto.getPassword());
            User userNew = new User();
            userNew.setPassword(new_user_pwd);
            userNew.setRegisterTime(new Date());
            userNew.setCreateTime(new Date());
            userNew.setAccount(registerDto.getAccount());
            userNew.setEmail(registerDto.getEmail());

            this.insert(userNew);
            productUserService.maybeSave(userNew);
//            this.relationDeviceFirstUseApp(userNew);

            //存在三方id 则注册到当前用户下
            if (StringUtils.isNotEmpty(registerDto.getThirdUserId())){
                UserThirdBind userThirdBind = userThirdBindMapper.getByTypeAndValue(registerDto.getThirdUserType(),registerDto.getThirdUserId());
                if(userThirdBind != null){
                    throw new BusinessException("三方用户已存在!");
                }

                if (StringUtils.equals(ThirdUserTypeEnum.wechat.name(),registerDto.getThirdUserType())){
                    if (StringUtils.isEmpty(userNew.getHeadImg()) || StringUtils.isEmpty(userNew.getNickname())) {
                        User wxUser = redisCache.getCacheObject(registerDto.getThirdUserId());
                        if (wxUser != null) {
                            if (StringUtils.isEmpty(userNew.getHeadImg())) {
                                userNew.setHeadImg(wxUser.getHeadImg());
                            }
                            if (StringUtils.isEmpty(userNew.getNickname())) {
                                userNew.setNickname(wxUser.getNickname());
                            }
                            userServiceImpl.update(userNew);
                        }
                    }
                }
                if(StringUtils.equals(ThirdUserTypeEnum.alipay.name(),registerDto.getThirdUserType())){
                    User aliUser = redisCache.getCacheObject(registerDto.getThirdUserId());
                    if (aliUser != null) {
                        if (StringUtils.isEmpty(userNew.getHeadImg())) {
                            userNew.setHeadImg(aliUser.getHeadImg());
                        }
                        if (StringUtils.isEmpty(userNew.getNickname())) {
                            userNew.setNickname(aliUser.getNickname());
                        }
                        if (userNew.getSex() == null || userNew.getSex() == 0) {
                            userNew.setSex(aliUser.getSex());
                        }
                        if (aliUser.getAccount() != null && userNew.getAccount().equals(aliUser.getAccount())) {
                            userNew.setAccountCheck(1);
                        }
                        userServiceImpl.update(userNew);
                    }
                }
                userThirdBind = new UserThirdBind();
                userThirdBind.setType(registerDto.getThirdUserType());
                userThirdBind.setValue(registerDto.getThirdUserId());
                userThirdBind.setUserId(userNew.getId());
                userThirdBindMapper.insert(userThirdBind);
            }

            return userNew.getId();
        }finally {
            distributedRidesLock.unlock(key,lock);
        }
    }

    /**
     * 用户注册关联设备首次使用应用
     * @param userNew
     */
    private void relationDeviceFirstUseApp(User userNew) {
        Device device = deviceServiceImpl.getByDeviceIdentify(DeviceContext.getDeviceIdentify());
        if (device == null){
            return;
        }
        Product product = productServiceImpl.getByPackageKey(DeviceContext.getProductPackageKey());
        if (product == null){
            return;
        }
        device.setFirstUseApp(product.getId().toString());
        deviceServiceImpl.update(device);
    }

    @Override
    public User login(LoginDto loginDto) {
        User userOld = this.getUserByVague(loginDto.getAccount());
        if(userOld == null){
            throw new BusinessException("查询不到您输入的账号，如果您还没有注册，请您点击下方“现在注册”！");
        }
        if(loginDto.getAccount().contains("@") && userOld.getEmailCheck() == 0) {
            throw new BusinessException("该邮箱还未验证，无法用于登录，请您使用手机号等其他方式登录。");
        }
        if (loginDto.getIsForce() != 0) {
            //存在三方id 则绑定到当前用户
            if (StringUtils.isNotEmpty(loginDto.getThirdUserId())){
                UserThirdBind userThirdBind = userThirdBindMapper.getByTypeAndValue(loginDto.getThirdUserType(),loginDto.getThirdUserId());
                if(userThirdBind != null){
                    throw new BusinessException("三方用户已存在!");
                }
                userThirdBind = userThirdBindMapper.getByTypeAndUserId(loginDto.getThirdUserType(),userOld.getId());
                if(userThirdBind != null){
                    if (loginDto.getIsUpdateThirdBind() == 0) {
                        userOld.setExistBind(1);
                        return userOld;
//                    logger.error("您输入的账号已绑定[QQ/微信/支付宝]登录方式，请您更换其他账号，或者点击下方“现在注册”。ThirdUserType:{};ThirdUserId:{}", loginDto.getThirdUserType(),loginDto.getThirdUserId());
//                    throw new BusinessException("您输入的账号已绑定[QQ/微信/支付宝]登录方式，请您更换其他账号，或者点击下方“现在注册”。");
                    } else {
                        userThirdBindMapper.deleteLogoutThirdBindById(userThirdBind.getId());
                        userThirdBindMapper.insertLogOutBackUp(userThirdBind);
                    }
                }
                if (StringUtils.equals(ThirdUserTypeEnum.wechat.name(),loginDto.getThirdUserType())){
                    if (StringUtils.isEmpty(userOld.getHeadImg()) || StringUtils.isEmpty(userOld.getNickname())) {
                        User wxUser = redisCache.getCacheObject(loginDto.getThirdUserId());
                        if (wxUser != null) {
                            if (StringUtils.isEmpty(userOld.getHeadImg())) {
                                userOld.setHeadImg(wxUser.getHeadImg());
                            }
                            if (StringUtils.isEmpty(userOld.getNickname())) {
                                userOld.setNickname(wxUser.getNickname());
                            }
                            userServiceImpl.update(userOld);
                        }
                    }
                }
                if(StringUtils.equals(ThirdUserTypeEnum.alipay.name(),loginDto.getThirdUserType())){
                    User aliUser = redisCache.getCacheObject(loginDto.getThirdUserId());
                    if (aliUser != null) {
                        if (StringUtils.isEmpty(userOld.getHeadImg())) {
                            userOld.setHeadImg(aliUser.getHeadImg());
                        }
                        if (StringUtils.isEmpty(userOld.getNickname())) {
                            userOld.setNickname(aliUser.getNickname());
                        }
                        if (userOld.getSex() == null || userOld.getSex() == 0) {
                            userOld.setSex(aliUser.getSex());
                        }
                        if (aliUser.getAccount() != null && userOld.getAccount().equals(aliUser.getAccount())) {
                            userOld.setAccountCheck(1);
                        }
                        userServiceImpl.update(userOld);
                    }
                }
                userThirdBind = new UserThirdBind();
                userThirdBind.setType(loginDto.getThirdUserType());
                userThirdBind.setValue(loginDto.getThirdUserId());
                userThirdBind.setUserId(userOld.getId());
                userThirdBindMapper.insert(userThirdBind);
            }
        }
        Product product = productServiceImpl.getByPackageKey(DeviceContext.getProductPackageKey());
        if (product != null && product.getLoginLimit() != null && product.getLoginLimit() > 0) {
            LinkedHashMap<String, String> userMap = redisCache.getCacheObject(userOld.getUserIdentify() + "_" + DeviceContext.getProductPackageKey());
            if (userMap != null && userMap.size() > 0) {
                LinkedHashMap<String, String> newUserMap = new LinkedHashMap<>();
                if (!userMap.containsKey(DeviceContext.getDeviceIdentify())) {
                    for (String userKey : userMap.keySet()) {
                        try {
                            if (redisCache.hasKey(userMap.get(userKey))) {
                                newUserMap.put(userKey, userMap.get(userKey));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (newUserMap.size() >= product.getLoginLimit()) {
                        if (loginDto.getIsForce() == 0) {
                            throw new BusinessException("您的账号登录的设备数量已达上限，登录失败。", 1001);
                        } else {
                            LinkedHashMap<String, String> tempMap = new LinkedHashMap<>();
                            ListIterator<Map.Entry<String,String>> i = new ArrayList<>(newUserMap.entrySet()).listIterator(newUserMap.size());
                            int index = 1;
                            while(i.hasPrevious()) {
                                if (index > product.getLoginLimit() - 1) {
                                    break;
                                }
                                Map.Entry<String, String> entry=i.previous();
                                System.out.println(entry.getKey()+":"+entry.getValue());
                                tempMap.put(entry.getKey(), entry.getValue());
                                index ++;
                            }
                            newUserMap = tempMap;
                        }
                    }
                } else {
                    newUserMap.putAll(userMap);
                }
                redisCache.setCacheObject(userOld.getUserIdentify() + "_" + DeviceContext.getProductPackageKey(), newUserMap);
            }
        }
        String password = Md5Utils.hash(loginDto.getPassword());
        if(!StringUtils.equals(userOld.getPassword(),password)){
            throw new BusinessException("密码不正确，请您重新输入。");
        }
        return userOld;
    }

    @Override
    public User mobielLogin(String token, String phoneNumber, Integer isForce) {
        User userOld = this.getByAccount(phoneNumber);
        if(userOld == null){
            return null;
        }
        Product product = productServiceImpl.getByPackageKey(DeviceContext.getProductPackageKey());
        if (product != null && product.getLoginLimit() != null && product.getLoginLimit() > 0) {
            LinkedHashMap<String, String> userMap = redisCache.getCacheObject(userOld.getUserIdentify() + "_" + DeviceContext.getProductPackageKey());
            if (userMap != null && userMap.size() > 0) {
                LinkedHashMap<String, String> newUserMap = new LinkedHashMap<>();
                if (!userMap.containsKey(DeviceContext.getDeviceIdentify())) {
                    for (String userKey : userMap.keySet()) {
                        try {
                            if (redisCache.hasKey(userMap.get(userKey))) {
                                newUserMap.put(userKey, userMap.get(userKey));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (newUserMap.size() >= product.getLoginLimit()) {
                        if (isForce== 0) {
                            redisCache.setCacheObject("mobielLogin" + token, phoneNumber, 5, TimeUnit.MINUTES);
                            throw new BusinessException("您的账号登录的设备数量已达上限，登录失败。", 1001);
                        } else {
                            LinkedHashMap<String, String> tempMap = new LinkedHashMap<>();
                            ListIterator<Map.Entry<String,String>> i = new ArrayList<>(newUserMap.entrySet()).listIterator(newUserMap.size());
                            int index = 1;
                            while(i.hasPrevious()) {
                                if (index > product.getLoginLimit() - 1) {
                                    break;
                                }
                                Map.Entry<String, String> entry=i.previous();
                                System.out.println(entry.getKey()+":"+entry.getValue());
                                tempMap.put(entry.getKey(), entry.getValue());
                                index ++;
                            }
                            newUserMap = tempMap;
                        }
                    }
                } else {
                    newUserMap.putAll(userMap);
                }
                redisCache.setCacheObject(userOld.getUserIdentify() + "_" + DeviceContext.getProductPackageKey(), newUserMap);
            }
        }
        return userOld;
    }

    /**
     * 邮箱验证
     * @param random
     */
    @Override
    public void verification(String random) {
        String account = emailSendCodeServiceImpl.checkEmailRegister(EmailCodeTypeEnum.EMAIL_VERIFIC.getCode(),random);
        if(StringUtils.isEmpty(account)){
            throw new BusinessException("邮箱验证失败");
        }
        User user = this.getByEmail(account);
        if (user == null){
            throw new BusinessException("用户不存在");
        }
        if (user.getEmailCheck() == 1){
            throw new BusinessException("邮箱已验证",1);
        }
        User userNew = new User();
        userNew.setId(user.getId());
        userNew.setEmailCheck(1);
        //此处自己调用自己为了清除缓存
        int count = userServiceImpl.saveOrUpdate(userNew);
        if(count <=0){
            throw new BusinessException("更新失败");
        }
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @Override
    public void updateUserInfo(User user) {
       User userOld = selectUserById(user.getId());
       if(userOld == null){
           throw new BusinessException("用户查询失败。");
       }
       if (StringUtils.isNotEmpty(user.getName())){
           userOld.setName(user.getName());
       }
        if (user.getBirthday() != null){
            userOld.setBirthday(user.getBirthday());
        }
        if (user.getSex() != null){
            userOld.setSex(user.getSex());
        }
        if (StringUtils.isNotEmpty(user.getCountry())){
            userOld.setCountry(user.getCountry());
        }
        if (StringUtils.isNotEmpty(user.getProvinceCode())){
            userOld.setProvinceCode(user.getProvinceCode());
        }
        if (StringUtils.isNotEmpty(user.getCityCode())){
            userOld.setCityCode(user.getCityCode());
        }
        if (StringUtils.isNotEmpty(user.getCountyCode())){
            userOld.setCountyCode(user.getCountyCode());
        }
        if (StringUtils.isNotEmpty(user.getAddress())){
            userOld.setAddress(user.getAddress());
        }
        if (StringUtils.isNotEmpty(user.getBloodType())){
            userOld.setBloodType(user.getBloodType());
        }
        if (StringUtils.isNotEmpty(user.getHeadImg())){
            userOld.setHeadImg(user.getHeadImg());
        }
        if (StringUtils.isNotEmpty(user.getNickname())){
            userOld.setNickname(user.getNickname());
        }
        int count = userMapper.update(userOld);
        if(count <= 0){
            throw new BusinessException("修改失败。");
        }
    }

    /**
     * 修改密码
     * @param userId
     * @param updatePwdDto
     * @return
     */
    @Override
    public Boolean updateUserPwd(Long userId, UpdatePwdDto updatePwdDto) {
        User userNew = new User();
        userNew.setId(userId);
        userNew.setPassword(Md5Utils.hash(updatePwdDto.getNewPwd()));
        int count = userMapper.update(userNew);
        return count == 1;
    }

    @Override
    public User getByThirdUserId(String thirdUserId) {
        return userMapper.getByThirdUserId(thirdUserId);
    }


    /**
     * 重置密码
     * @param resetPwdDto
     * @return
     */
    @Override
    public void resetUserPwd(ResetPwdDto resetPwdDto) {

        User userOld = this.getUserByVague(resetPwdDto.getAccount());
        if (userOld == null){
            throw new BusinessException("用户查询失败。");
        }
        if (resetPwdDto.getVerifyType() == 0) {
            emailSendCodeServiceImpl.checkEmailCode(EmailCodeTypeEnum.UP_PASS.getCode(),userOld.getEmail(),resetPwdDto.getCode());
        }

        User userNew = new User();
        userNew.setId(userOld.getId());
        userNew.setPassword(Md5Utils.hash(resetPwdDto.getNewPwd()));
        //此处自己调用自己为了清除缓存
        int count = userServiceImpl.saveOrUpdate(userNew);
        if(count <= 0){
            throw new BusinessException("修改失败。");
        }
    }

    @Override
    public User getUserByVague(String accountOrEmail) {
        if(accountOrEmail.contains("@")){
            return this.getByEmail(accountOrEmail);
        }else{
            return this.getByAccount(accountOrEmail);
        }
    }

    @Override
    public List<User> getByIds(Set<Long> userIdSet) {
        return userMapper.getByIds(userIdSet);
    }

    @Override
    @Transactional
    public void logOutAccount(Long userId,String password,String reason) {
        User user = this.selectUserById(userId);
        if (user == null){
            throw new BusinessException("用户查询失败");
        }

        if(!StringUtils.equals(user.getPassword(),Md5Utils.hash(password))){
            throw new BusinessException("密码输入错误，请重新输入。");
        }

        //删除账号  备份账号
        userMapper.logoutAccountById(userId);
        UserBackUpDto userBackUpDto = new UserBackUpDto();
        BeanUtils.copyProperties(user,userBackUpDto);
        userBackUpDto.setReason(reason);
        userBackUpDto.setLogoutApp(productServiceImpl.getByPackageKey(DeviceContext.getProductPackageKey()).getName());
        userMapper.insertLogOutBackUp(userBackUpDto);

        //删除 三方绑定账号   备份三方绑定账号
        UserThirdBind userThirdBind = new UserThirdBind();
        userThirdBind.setUserId(userId);
        List<UserThirdBind> userThirdBindList = userThirdBindMapper.selectUserThirdBindList(userThirdBind);
        if (CollectionUtils.isNotEmpty(userThirdBindList)){
            for(UserThirdBind thirdBind:userThirdBindList){

                userThirdBindMapper.deleteLogoutThirdBindById(thirdBind.getId());

                userThirdBindMapper.insertLogOutBackUp(thirdBind);
            }
        }
    }

    /**
     * 查询用户信息列表
     *
     * @param user 用户信息
     * @return 用户信息
     */
    @Override
    public List<UserBackUpDto> selectLogOutPageList(User user)
    {
        return userMapper.selectLogOutUserList(user);
    }

    @Override
    public User selectLogoutUserById(Long id) {
        return userMapper.selectLogoutUserById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateAccount(UpdateAccountDto updateAccountDto) {
        Long userId = ShiroUtils.getUserId();
        User userOld = this.selectUserById(userId);
        if (userOld == null){
            throw new BusinessException("用户查询失败。", 10009);
        }
        User sameUser = this.getByAccount(updateAccountDto.getNewAccount());
        if (sameUser != null && !userOld.getId().equals(sameUser.getId())) {
            if (updateAccountDto.getIsMerge() == 0) {
                throw new BusinessException("手机号已有账号，是否需要将原账号合并。", 10010);
            } else {
//                合并
//                查询订阅关系
                UserSubRecord userSubRecord = new UserSubRecord();
                userSubRecord.setUserId(sameUser.getId());
                userSubRecord.setStatus(1);
                List<UserSubRecord> records = userSubRecordMapper.selectUserSubRecordList(userSubRecord).getResult();
                if (records != null && records.size() > 0) {
//                    原账户有有效订阅关系
                    userSubRecord.setUserId(userId);
                    List<UserSubRecord> newRecords = userSubRecordMapper.selectUserSubRecordList(userSubRecord).getResult();
                    if (newRecords == null || newRecords.size() == 0) {
//                      新账户无有效订阅关系
                        records.forEach(e -> {
                            e.setUserId(userId);
                            userSubRecordMapper.update(e);
                            logger.error("合并账户{}到{}（新账户无订阅关系），更新订阅关系{}", sameUser.getUserIdentify(), userOld.getUserIdentify(), e);
                        });
                    } else {
    //                  新账户有有效订阅关系
                        Set<String> s = new HashSet<>();
                        records.forEach(e -> {
                            newRecords.forEach(e1 ->{
                                if (e1.getProductId().equals(e.getProductId()) && e1.getGoodsTypeId().equals(e.getGoodsTypeId())) {
                                    int day = DateUtils.differentDaysByMillisecond(e.getEffictStartTime(), e.getEffictEndTime());
                                    e1.setEffictEndTime(DateUtils.addDays(e1.getEffictEndTime(), day));
                                    userSubRecordMapper.update(e1);
                                    logger.error("合并账户{}到{}（新账户有订阅关系），更新订阅关系{}到{}", sameUser.getUserIdentify(), userOld.getUserIdentify(), e, e1);
                                }
                            });
                        });
                    }
                }
                this.deleteById(sameUser.getId());
                if (StringUtils.isEmpty(userOld.getEmail()) && StringUtils.isNotEmpty(sameUser.getEmail())) {
                    userOld.setEmail(sameUser.getEmail());
                }
                if (userOld.getEmailCheck() == null && sameUser.getEmailCheck() != null) {
                    userOld.setEmailCheck(sameUser.getEmailCheck());
                }
                if (StringUtils.isEmpty(userOld.getNickname()) && StringUtils.isNotEmpty(sameUser.getNickname())) {
                    userOld.setNickname(sameUser.getNickname());
                }
                if (StringUtils.isEmpty(userOld.getHeadImg()) && StringUtils.isNotEmpty(sameUser.getHeadImg())) {
                    userOld.setHeadImg(sameUser.getHeadImg());
                }
                if (StringUtils.isEmpty(userOld.getName()) && StringUtils.isNotEmpty(sameUser.getName())) {
                    userOld.setName(sameUser.getName());
                }
                if (userOld.getSex() == null && sameUser.getSex() != null) {
                    userOld.setSex(sameUser.getSex());
                }
                if (userOld.getBirthday() == null && sameUser.getBirthday() != null) {
                    userOld.setBirthday(sameUser.getBirthday());
                }
                if (StringUtils.isEmpty(userOld.getProvinceCode()) && StringUtils.isNotEmpty(sameUser.getProvinceCode())) {
                    userOld.setProvinceCode(sameUser.getProvinceCode());
                }
                if (StringUtils.isEmpty(userOld.getCityCode()) && StringUtils.isNotEmpty(sameUser.getCityCode())) {
                    userOld.setCityCode(sameUser.getCityCode());
                }
                if (StringUtils.isEmpty(userOld.getCountyCode()) && StringUtils.isNotEmpty(sameUser.getCountyCode())) {
                    userOld.setCountyCode(sameUser.getCountyCode());
                }
                if (StringUtils.isEmpty(userOld.getAddress()) && StringUtils.isNotEmpty(sameUser.getAddress())) {
                    userOld.setAddress(sameUser.getAddress());
                }
                if (StringUtils.isEmpty(userOld.getBloodType()) && StringUtils.isNotEmpty(sameUser.getBloodType())) {
                    userOld.setBloodType(sameUser.getBloodType());
                }
                userOld.setAccount(updateAccountDto.getNewAccount());
                userOld.setAccountCheck(0);
                userOld.setUpdateTime(new Date());
                int count = this.update(userOld);
                return count == 1;
            }
        }
        User tempUser = new User();
        tempUser.setId(userId);
        tempUser.setAccount(updateAccountDto.getNewAccount());
        tempUser.setAccountCheck(0);
        tempUser.setUpdateTime(new Date());
        int count = this.update(tempUser);
        return count == 1;
    }

    @Override
    public Boolean updateUserEmail(UpdateEmailDto updateEmailDto) {
        Long userId = ShiroUtils.getUserId();
        User userOld = this.selectUserById(userId);
        if (userOld == null){
            throw new BusinessException("用户查询失败。", 10009);
        }
        User tempUser = new User();
        tempUser.setId(userId);
        tempUser.setEmail(updateEmailDto.getNewEmail());
        tempUser.setEmailCheck(0);
        tempUser.setUpdateTime(new Date());
        int count = this.update(tempUser);
        SendCodeDto sendCodeDto = new SendCodeDto();
        sendCodeDto.setType("email");
        sendCodeDto.setAccount(updateEmailDto.getNewEmail());
        emailSendCodeServiceImpl.sendEmailCode(sendCodeDto);
        return count == 1;
    }
}
